/////////////////////////////////////////////////////////////////////////////
// Original code from libhdfs3. Copyright (c) 2013 - 2014, Pivotal Inc.
// All rights reserved. Author: Zhanwei Wang
/////////////////////////////////////////////////////////////////////////////
//  Modifications by Kumo Inc.
// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <ktest/ktest.h>
#include <kmock/kmock.h>

#include <kmhdfs/common/exception.h>
#include <tests/mock/mock_buffered_socket_reader.h>
#include <tests/mock/mock_rpc_channel.h>
#include <tests/mock/mock_socket.h>
#include <kmhdfs/rpc/rpc_client.h>
#include <tests/mock/test_rpcchannel_stub.h>
#include <tests/unit/unit_test_utils.h>
#include <kmhdfs/common/xml_config.h>

using namespace Hdfs;
using namespace Hdfs::Mock;
using namespace Hdfs::Internal;
using namespace testing;

class MockRpcChannelStub: public TestRpcChannelStub {
public:
    MOCK_METHOD2(getChannel, RpcChannel * (
                     RpcChannelKey key, RpcClient & c));
};

static RpcChannelKey BuildKey() {
    RpcAuth auth;
    RpcProtocolInfo protocol(0, "test", "kind");
    RpcServerInfo server("unknown token service", "unknown server", "unknown port");
    Config conf;
    SessionConfig session(conf);
    RpcConfig rpcConf(session);
    return RpcChannelKey(auth, protocol, server, rpcConf);
}

static RpcConfig & GetConfig(RpcChannelKey & key) {
    return const_cast<RpcConfig &>(key.getConf());
}

TEST(TestRpcClient, TestInvoke_CreateChannelFailure) {
    RpcAuth auth;
    RpcProtocolInfo protocol(0, "test", "kind");
    RpcServerInfo server("unknown token service", "unknown server", "unknown port");
    Config conf;
    SessionConfig session(conf);
    RpcConfig rpcConf(session);
    MockRpcChannelStub stub;
    RpcClientImpl client;
    client.stub = &stub;
    EXPECT_CALL(stub, getChannel(_, _)).Times(1).WillOnce(
        InvokeWithoutArgs(
            bind(&InvokeThrowAndReturn<HdfsIOException, RpcChannel *>,
                 "create channel failed.", static_cast<bool *>(NULL),
                 static_cast<RpcChannel *>(NULL))));
    EXPECT_THROW(client.getChannel(auth, protocol, server, rpcConf),
                 HdfsRpcException);
}

TEST(TestRpcClient, TestCleanupIdleChannel) {
    RpcAuth auth;
    RpcProtocolInfo protocol(0, "test", "kind");
    RpcServerInfo server("unknown token service", "unknown server", "unknown port");
    Config conf;
    SessionConfig session(conf);
    RpcConfig rpcConf(session);
    MockRpcChannelStub stub;
    RpcClientImpl client;
    client.stub = &stub;
    RpcChannelKey key = BuildKey();
    GetConfig(key).setMaxIdleTime(10000);
    GetConfig(key).setPingTimeout(900);
    MockSocket * sock = new MockSocket();
    MockBufferedSocketReader * in = new MockBufferedSocketReader();
    RpcChannelImpl * channel = new RpcChannelImpl(key, sock, in, client);
    EXPECT_CALL(stub, getChannel(_, _)).Times(1).WillOnce(Return(channel));
    channel->lastActivity = channel->lastIdle = steady_clock::now();
    channel->available = true;
    EXPECT_CALL(*sock, close()).Times(AtLeast(1));
    EXPECT_CALL(*sock, writeFully(_, _, _)).Times(AtLeast(1));
    sleep_for(seconds(1));
    EXPECT_NO_THROW(client.getChannel(auth, protocol, server, rpcConf));
    EXPECT_TRUE(channel->refs == 1);
    channel->close(false);
    sleep_for(seconds(3));
}
